//
//  TSLoginViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/11/7.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import HandyJSON

struct TSCodeModel : HandyJSON {
    var img : String?
    var num = 0
    var id = 0
}

class TSLoginViewController: TSBaseViewController {

    var accountField : UITextField!
    var pwdField : UITextField!
    var codeImg : UIImageView!
    var codeField : UITextField!
    var model : TSCodeModel? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configViews()
        getVertifyCode()
    }
    
    @objc func tapGesture(gesture:UITapGestureRecognizer) {
        
        getVertifyCode()
    }
    
    @objc func loginAction() {
        
        guard accountField.text?.count != 0 else {
            CBToast.showToastAction(message: "请输入账号")
            return
        }
        
        guard pwdField.text?.count != 0 else {
            CBToast.showToastAction(message: "请输入密码")
            return
        }
        
        guard codeField.text?.count != 0 else {
            CBToast.showToastAction(message: "请输入验证码")
            return
        }
        
        if self.model == nil {
            CBToast.showToastAction(message: "请获取验证码")
            return;
        }
        
        IQKeyboardManager.shared().resignFirstResponder()
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.login(username: accountField.text!, verifyCode: codeField.text!, password: pwdField.text!, capid: "\(self.model!.id)"), showHUD: true, success: { (data) in

            CBToast.hiddenToastAction()
            
            let responseDic = data as? NSDictionary
            
            TSLoginManager.shared.token = responseDic?.object(forKey: "token") as? String
            TSLoginManager.shared.user_id = responseDic?.object(forKey: "user_id") as! Int

            UIApplication.shared.keyWindow?.rootViewController = TSTabbarController()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }

}

extension TSLoginViewController {
    
    func configViews() {
        let img = UIImageView.init(image: UIImage(named: "login_bg"))
        view.addSubview(img)
        img.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(336+STATUSBAR_HEIGHT)
        }
        
        accountField = createInputField(placeholder: "请输入用户名")
    #if DEBUG 
        accountField.text = "111111"
    #else
        
    #endif
        
        view.addSubview(accountField)
        accountField.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(340*T_ScreenScale())
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.61, height: 50))
        }
        
        let accountImg = UIImageView.init(image: UIImage(named: "login_username"))
        view.addSubview(accountImg)
        accountImg.snp.makeConstraints { (make) in
            make.centerY.equalTo(accountField)
            make.right.equalTo(accountField.snp_left).offset(-15)
            make.size.equalTo(CGSize(width: 14, height: 17))
        }
        
        let line1 = drawLine()
        view.addSubview(line1)
        line1.snp.makeConstraints { (make) in
            make.left.equalTo(accountField).offset(-5)
            make.right.equalTo(accountField).offset(5)
            make.top.equalTo(accountField.snp_bottom)
            make.height.equalTo(1)
        }
        
        pwdField = createInputField(placeholder: "请输入密码")
        pwdField.isSecureTextEntry = true
        #if DEBUG 
            pwdField.text = "111111"
        #else
            
        #endif
        view.addSubview(pwdField)
        pwdField.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(line1.snp_bottom).offset(5)
            make.size.equalTo(accountField)
        }
        
        let pwdImg = UIImageView.init(image: UIImage(named: "login_password"))
        view.addSubview(pwdImg)
        pwdImg.snp.makeConstraints { (make) in
            make.centerY.equalTo(pwdField)
            make.right.equalTo(pwdField.snp_left).offset(-15)
            make.size.equalTo(accountImg)
        }
        
        let line2 = drawLine()
        view.addSubview(line2)
        line2.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(line1)
            make.top.equalTo(pwdField.snp_bottom)
        }
        
        codeField = createInputField(placeholder: "请输入验证码")
        codeField.keyboardType = .phonePad
        view.addSubview(codeField)
        codeField.snp.makeConstraints { (make) in
            make.left.equalTo(accountImg)
            make.top.equalTo(line2.snp_bottom).offset(5)
            make.width.equalTo(accountField.snp_width).multipliedBy(0.5)
            make.height.equalTo(accountField)
        }
        
        let line3 = drawLine()
        view.addSubview(line3)
        line3.snp.makeConstraints { (make) in
            make.left.right.equalTo(codeField)
            make.top.equalTo(codeField.snp_bottom)
            make.height.equalTo(1)
        }
        
        codeImg = UIImageView.init()
        codeImg.isUserInteractionEnabled = true
        codeImg.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(tapGesture(gesture:))))
        view.addSubview(codeImg)
        codeImg.snp.makeConstraints { (make) in
            make.left.equalTo(line3.snp_right).offset(5)
            make.bottom.equalTo(line3)
            make.right.equalTo(line2)
            make.height.equalTo(45)
        }
        
        let loginBtn = UIButton.init(type: .system)
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.setTitleColor(WHITE_COLOR, for: .normal)
        loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        loginBtn.backgroundColor = BASE_PURPLE_COLOR
        loginBtn.layer.cornerRadius = 22
        loginBtn.layer.masksToBounds = true
        loginBtn.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(line3.snp_bottom).offset(30*T_ScreenScale())
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.677, height: 44))
        }
        
    }
    
    func createInputField(placeholder:String) -> UITextField {
        
        let string = placeholder
        let attributeStr = NSMutableAttributedString.init(string: string)
        attributeStr.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.hexadecimalColor(hexadecimal: "#CCCCCC"), NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: .medium)], range: NSMakeRange(0, string.count))
        
        let textField = UITextField.init()
        textField.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        textField.textColor = UIColor.hexadecimalColor(hexadecimal: "#282828")
        textField.attributedPlaceholder = (attributeStr.copy() as! NSAttributedString)
        textField.borderStyle = .none
        textField.clearButtonMode = .whileEditing
        return textField
    }
    
    func drawLine() -> UIView {
        let line = UIView.init()
        line.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#E2E4E8")
        return line
    }
    
    func getVertifyCode() {
        
        TSNetworkManager.request(TMSNetworkTools.getVertifyCode, showHUD: true, success: { (data) in
            
            let responseDic = data as? NSDictionary
            
            let model = TSCodeModel.deserialize(from: responseDic)
            self.model = model
            
            self.codeImg.sd_setImage(with: URL(string: model?.img ?? ""), completed: nil)
            
        }) { (error) in
            
        }
    }
}
